const express = require('express')
const axios = require("axios")
const fs = require("fs")
const util = require('./util')
const path = require("path")
const codes = require('../static/codes.json')
const worldLocation = require('../static/worldLocation.json')
const app = express()
const port = 3000

app.all('*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*')
        // Access-Control-Allow-Headers ,可根据浏览器的F12查看,把对应的粘贴在这里就行
    res.header('Access-Control-Allow-Headers', 'Content-Type')
    res.header('Access-Control-Allow-Methods', '*')
    next()
})

app.use('/', express.static(path.join(__dirname, '../dist')))

const config = {
    url: 'https://ncovdata.market.alicloudapi.com/ncov/cityDiseaseInfoWithTrend',
    appCode: '33626c2edb374efa80546462021b10cd',
    appKey: '203881076',
    appSecret: 'UhzJaqkZZFhmGN7Wgx4gBpNAEdeTTPEF'
}

const worldUrl = 'https://api.inews.qq.com/newsqa/v1/automation/foreign/country/ranklist'


//更新中国数据
function updateChina() {
    return new Promise((resolve, reject) => {
        axios.get(config.url, { headers: { authorization: `APPCODE ${config.appCode}` } }).then(result => {
            if (result.headers['content-type'].startsWith('text/html')) {
                console.log(result.data)
                reject(result)
            } else {
                util.writeData(path.join(__dirname, "../static/countryData.json"), result.data).then(() => {
                    return writeGeoJson(result.data)
                }).then(() => {
                    console.log(result.data)
                    resolve(result.data)
                }).catch(reason => {
                    console.log(reason)
                    reject(reason)
                })
            }
        })

    })
}

//更新全球数据
function updateWorld(chinaData) {
    return new Promise(async(resolve, reject) => {
        let result = await axios.get(worldUrl)

        let countryData = JSON.parse(chinaData).country
        result.data.data.push({
            'name': '中华人民共和国',
            'confirm': countryData.totalConfirmed,
            'dead': countryData.totalDeath,
            'heal': countryData.totalCured,
            'confirmAdd': countryData.totalIncrease
        })

        util.writeData(path.join(__dirname, "../static/worldData.json"), result.data, err => {
            if (err) {
                reject(err.message)
            } else {
                resolve()
            }
        })
    })
}

//格式化中国GeoJson
function writeGeoJson(data) {
    return new Promise((resolve, reject) => {
        let geoJson = {
            'type': 'FeatureCollection',
            'crs': {
                'type': 'name',
                'properties': {
                    'name': 'urn:ogc:def:crs:OGC:1.3:CRS84'
                }
            },
            'features': []
        }
        data['provinceArray'].forEach(province => {
            if (!codes[province['childStatistic']]) {
                console.log('')
            }
            geoJson.features.push({
                'type': 'Feature',
                'properties': province,
                'geometry': {
                    'type': 'Point',
                    'coordinates': codes[province['childStatistic']]['coordinates']
                }
            })
        })
        util.writeData(path.join(__dirname, "../static/geoJson.json"), geoJson).then(err => {
            if (err) reject(err)
            else resolve()
        })
    })
}

//格式化全球GeoJson
function writeWorldGeoJson(countries) {
    return new Promise((resolve, reject) => {
        let geoJson = {
            'type': 'FeatureCollection',
            'crs': {
                'type': 'name',
                'properties': {
                    'name': 'urn:ogc:def:crs:OGC:1.3:CRS84'
                }
            },
            'features': []
        }
        countries.data.forEach(country => {
            let location = worldLocation[country.name]
            if (location) {
                geoJson.features.push({
                    'type': 'Feature',
                    'properties': country,
                    'geometry': {
                        'type': 'Point',
                        'coordinates': [location.lng, location.lat]
                    }
                })
            }
        })

        util.writeData(path.join(__dirname, "../static/worldGeo.json"), geoJson, err => {
            if (err) {
                console.error(err)
                reject(err)
            } else resolve()
        })
    })
}

//国内疫情数据接口
app.get('/getCovid19Data', async(req, res) => {
    let data = await util.readDate(path.join(__dirname, "../static/countryData.json"))
    updateWorld(data)
    writeGeoJson(JSON.parse(data))
    let color = [{
            colorNum: "#FF4818",
            colorSection: ">4800",
        },
        {
            colorNum: "#fc5a31",
            colorSection: "2400 ~ 4800",
        },
        {
            colorNum: "#fa6641",
            colorSection: "1280 ~ 2400",
        },
        {
            colorNum: "#fa6641",
            colorSection: "640 ~ 1280",
        },
        {
            colorNum: "#fd8e72",
            colorSection: "320 ~ 640",
        },
        {
            colorNum: "#ff947a",
            colorSection: "160 ~ 320",
        },
        {
            colorNum: "#ffa088",
            colorSection: "80 ~ 160",
        },
        {
            colorNum: "#f5ad9b",
            colorSection: "40 ~ 80",
        },
        {
            colorNum: "#f3b9aa",
            colorSection: "20 ~ 40",
        },
        {
            colorNum: "#fcd2c8",
            colorSection: "10 ~ 20",
        },
        {
            colorNum: "#f7ded7",
            colorSection: "<10",
        },
    ]
    data = JSON.parse(data)
    data.color = color
    if (data) {
        res.json({
            state: 200,
            message: "成功",
            data: data
        })
    } else {
        res.json({
            state: 400,
            message: "错误",
        })
    }
})

//世界疫情数据接口
app.get('/getWorldCovid19Data', async(req, res) => {
    let data = await util.readDate(path.join(__dirname, "../static/worldData.json"))
    writeWorldGeoJson(JSON.parse(data))
    let color = [{
            colorNum: "#FF4818",
            colorSection: ">4800000",
        },
        {
            colorNum: "#fc5a31",
            colorSection: "2400000 ~ 4800000",
        },
        {
            colorNum: "#fa6641",
            colorSection: "1280000 ~ 2400000",
        },
        {
            colorNum: "#fa6641",
            colorSection: "640000 ~ 1280000",
        },
        {
            colorNum: "#fd8e72",
            colorSection: "320000 ~ 640000",
        },
        {
            colorNum: "#ff947a",
            colorSection: "160000 ~ 320000",
        },
        {
            colorNum: "#ffa088",
            colorSection: "80000 ~ 160000",
        },
        {
            colorNum: "#f5ad9b",
            colorSection: "40000 ~ 80000",
        },
        {
            colorNum: "#f3b9aa",
            colorSection: "20000 ~ 40000",
        },
        {
            colorNum: "#fcd2c8",
            colorSection: "10000 ~ 20000",
        },
        {
            colorNum: "#f7ded7",
            colorSection: "<10000",
        },
    ]
    data = JSON.parse(data)
    data.color = color
    if (data) {
        res.json({
            state: 200,
            message: "成功",
            data: data
        })
    } else {
        res.json({
            state: 400,
            message: "错误",
        })
    }
})

//国内GeoJson接口
app.get('/getGeoJson', (req, res) => {
    util.readDate(path.join(__dirname, "../static/geoJson.json")).then(data => {
        res.json({
            state: 200,
            message: "成功",
            data: JSON.parse(data)
        })
    }).catch(reason => {
        console.error(reason)
        res.json({
            state: 400,
            message: reason.message
        })
    })
})

//全球GeoJson接口
app.get('/getWorldGeoJson', (req, res) => {
    util.readDate(path.join(__dirname, "../static/worldGeo.json")).then(data => {
        res.json({
            state: 200,
            message: "成功",
            data: JSON.parse(data)
        })
    }).catch(reason => {
        console.error(reason)
        res.json({
            state: 400,
            message: reason.message
        })
    })
})

//刷新疫情数据接口
app.get('/reloadCovid19Data', async(req, res) => {
    let data = await updateChina()
    updateWorld(data)
    if (data) {
        res.json({
            state: 200,
            message: "成功",
            data: data
        })
    } else {
        res.json({
            state: 400,
            message: "错误",
        })
    }
})



app.listen(port, () => console.log(`serve on:http://127.0.0.1:3000`))